#include "GeometryDataMgrGLES.h"
#include "VertexBufferGLES.h"
#include "IndexBufferGLES.h"
#include "RendererGLES.h"

#define DEFAULT_VB_RESERVE 16
#define DEFAULT_IB_RESERVE 16
#define DEFAULT_SM_RESERVE 8

namespace Nezha
{

	GeometryDataMgrGLES::GeometryDataMgrGLES(RendererGLES* r)
		: mRenderer(r)
	{
	}

	GeometryDataMgrGLES::~GeometryDataMgrGLES()
	{
		releaseAllData();
	}

	VertexBufferPtr GeometryDataMgrGLES::createVertexBuffer(u32 vertexStride, u32 numVertex, HardwareBuffer::Usage usage, bool createShadowBuffer /* = false */, float* data /* = NULL */)
	{
		VertexBufferPtr ptr;

		VertexBufferGLES* vb = NZ_New VertexBufferGLES(vertexStride, numVertex, usage, mRenderer, data);
		ptr = vb;
		
		mVertexBuffers.push_back(ptr);

		return ptr;
	}

	IndexBufferPtr GeometryDataMgrGLES::createIndexBuffer(HardwareBuffer::Usage usage, IndexBuffer::IndexType it, u32 numIndices, bool createShadowBuffer /* = false */, u16* data /* = NULL */)
	{
		IndexBufferPtr ptr;

		IndexBufferGLES* ib = NZ_New IndexBufferGLES(usage, it, numIndices, mRenderer, data);
		ptr = ib;

		mIndexBuffers.push_back(ptr);

		return ptr;
	}

	//void GeometryDataMgrGLES::batchBuffers(PArray<GeometryData*>& buffers)
	//{
	//	// TODO
	//}

	void GeometryDataMgrGLES::_garbageDispose()
	{
		for(VBArray::iterator it = mVertexBuffers.begin(); it != mVertexBuffers.end(); )
		{
			if((*it)->getRefCount() == 1)
			{
				(*it).release();
				it = mVertexBuffers.erase(it);
			}
			else
			{
				it++;
			}
		}

		for(IBArray::iterator it = mIndexBuffers.begin(); it != mIndexBuffers.end(); )
		{
			if((*it)->getRefCount() == 1)
			{
				(*it).release();
				it = mIndexBuffers.erase(it);
			}
			else
			{
				it++;
			}
		}
	}

	void GeometryDataMgrGLES::releaseAllData()
	{
		for(VBArray::iterator it = mVertexBuffers.begin(); it != mVertexBuffers.end(); it++)
		{
			(*it).release();
		}

		for(IBArray::iterator it = mIndexBuffers.begin(); it != mIndexBuffers.end(); it++)
		{
			(*it).release();
		}

		mVertexBuffers.clear();
		mIndexBuffers.clear();
	}

}//end namespace Nezha